package com.kinon.tyjaccount.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kinon.tyjaccount.Constatus;
import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.data.DataModel;
import com.kinon.tyjaccount.data.UPacketFactory;
import com.kinon.tyjaccount.service.GetMakemealService;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.SharedPreferencesUtil;
import com.kinon.tyjaccount.tools.ToastUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.ICheckFileCallback;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.IReceiveCallback;
import sunmi.ds.callback.ISendCallback;
import sunmi.ds.callback.ISendFilesCallback;
import sunmi.ds.data.DSData;
import sunmi.ds.data.DSFile;
import sunmi.ds.data.DSFiles;
import sunmi.ds.data.DataPacket;

public class LoginActivity extends Activity implements OnClickListener{
	
	 /**登录*/
    Button btn_login;
	private Button btn_urgent;
    /**手机号*/
    private EditText et_phone;
    /**密码*/
    private EditText et_password;

	private static final String SHOW_IMG_LIST_ID = "SHOW_IMG_LIST_ID";
	private static final String WELCOME_IMG_ID = "WELCOME_IMG_ID";

	private final static String SHOW_VIDEO_LIST_DATA_ID = "SHOW_VIDEO_LIST_DATA_ID";
	private final static String SHOW_IMGS_LIST_DATA_ID = "SHOW_IMGS_LIST_DATA_ID";
	long taskId;
	String pathBig = Environment.getExternalStorageDirectory().getPath() + "/dcim/caizhengting.png";
	DSKernel mDSKernel;// SDK核心类
	DataPacket dsPacket;
	ToastUtil toastUtil=new ToastUtil();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initSDK();
		initRes();
//		Show();
	}
	
	private void initRes() {
        btn_login = (Button)findViewById(R.id.btn_login);
        et_phone = (EditText)findViewById(R.id.et_name);
        et_password = (EditText)findViewById(R.id.et_pwd);
		btn_urgent= (Button) findViewById(R.id.btn_urgent);
        SharedPreferences spuser=getSharedPreferences("spuser", Context.MODE_PRIVATE);
		if(!"".equals(spuser))
		{
			et_phone.setText(spuser.getString("phone", ""));
			et_password.setText(spuser.getString("pwd", ""));
		}
		/**登录*/
		btn_login.setOnClickListener(this);
		btn_urgent.setOnClickListener(this);
        /**登录*/

    }

	@Override
	public void onClick(View view) {
		switch (view.getId())
		{
			case R.id.btn_login:
				login();
				break;
			case R.id.btn_urgent:
				urgentLogin();
				break;
		}
	}

	/**紧急状态登录*/
	private void urgentLogin(){
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		String token = sp.getString("data", "");
		if(TextUtils.isEmpty(token)){
			Toast.makeText(getApplicationContext(),
					"用户token为空不能紧急登录",Toast.LENGTH_SHORT).show();
		}else{
			startAllService();

			Constatus.URGENT_TYPE=true;
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), MainActivity.class);
			startActivity(intent);
			finish();
		}
	}

	private void startAllService() {
		Intent intent = new Intent(this, GetMakemealService.class);
		startService(intent);
	}

	private void login(){
		if(NetWorkUtil.isNetwork(getApplicationContext())==false)
		{
			Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
			return;
		}
        String phone=et_phone.getText().toString();
        String pwd=et_password.getText().toString();
        if(TextUtils.isEmpty(phone)){
            Toast.makeText(LoginActivity.this,"账号为空",Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(pwd)){
            Toast.makeText(LoginActivity.this,"密码为空",Toast.LENGTH_SHORT).show();
            return;
        }
        HttpTools httptools=new HttpTools(getApplicationContext());
		httptools.login(phone, pwd,"3,5", new JsonLogin());

    }
	private class JsonLogin extends JsonHttpResponseHandler{
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			try {
				boolean code=response.getBoolean("code");
				String msg=response.getString("msg");
				if(code==true){
					Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
					String data=response.getString("data");
					Log.i("shi", data);
					SharedPreferences spReg = getSharedPreferences("spReg",
							Context.MODE_PRIVATE);
					Editor editor = spReg.edit();
					editor.putString("data", data);
					editor.commit();

					//启动获取取餐订单信息服务
					startAllService();
					
					SharedPreferences spuser = getSharedPreferences("spuser",
							Context.MODE_PRIVATE);
					Editor editoruser = spuser.edit();
					editoruser.putString("phone", et_phone.getText().toString());
					editoruser.putString("pwd", et_password.getText().toString());
					editoruser.commit();
					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), MainActivity.class);
					startActivity(intent);
					finish();
				}else{
					Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		@Override
		public void onFailure(Throwable e, JSONObject errorResponse) {
			super.onFailure(e, errorResponse);
			Toast.makeText(LoginActivity.this,
					"网络请求失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
	        if((System.currentTimeMillis()-exitTime) > 2000){  
	            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();                                
	            exitTime = System.currentTimeMillis();   
	        } else {
	            finish();
	            System.exit(0);
	        }
	        return true;   
	    }
	    return super.onKeyDown(keyCode, event);
	}

	/**以下为副屏显示*/
	private void initSDK() {
		mDSKernel = DSKernel.newInstance();
		mDSKernel.init(this, mConnCallback);
		showWelcomeImage();
	}
	IConnectionCallback mConnCallback = new IConnectionCallback() {// SDK链接状态回调
		@Override
		public void onDisConnect() {
		}

		@Override
		public void onConnected(final ConnState state) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
//					Toast.makeText(MainActivity.this, "state:"+state, Toast.LENGTH_LONG).show();
					switch (state) {
						case AIDL_CONN:
							//与本地service的连接畅通
							break;
						case VICE_SERVICE_CONN:
							//与副屏service连接畅通
							long fileId = SharedPreferencesUtil.getLong(LoginActivity.this, SHOW_IMG_LIST_ID);
							long fileId1 = SharedPreferencesUtil.getLong(LoginActivity.this, WELCOME_IMG_ID);
							long fileId2 = SharedPreferencesUtil.getLong(LoginActivity.this,SHOW_VIDEO_LIST_DATA_ID);
							long fileId3 = SharedPreferencesUtil.getLong(LoginActivity.this,SHOW_IMGS_LIST_DATA_ID);
							if(fileId2!=-1L)checkImg(fileId2,SHOW_VIDEO_LIST_DATA_ID);
							if(fileId3!=-1L)checkImg(fileId3,SHOW_IMGS_LIST_DATA_ID);
							if(fileId!=-1L)checkImg(fileId, SHOW_IMG_LIST_ID);
							if(fileId1!=-1L) checkImg(fileId1, WELCOME_IMG_ID);
							break;
						case VICE_APP_CONN:
							//与副屏app连接畅通
							break;

						default:
							break;
					}

				}
			});
		}
	};
	private void checkImg(long fileId, final String key){

		mDSKernel.checkFileExist(fileId, new ICheckFileCallback() {
			@Override
			public void onCheckFail() {
//				Toast.makeText(MainActivity.this, key + " 文件不存在", Toast.LENGTH_LONG).show();
			}

			@Override
			public void onResult(boolean b) {
				if(!b){
					SharedPreferencesUtil.put(LoginActivity.this, key, -1L);
				}else{
//					Toast.makeText(MainActivity.this, key + " 文件存在", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	private void showWelcomeImage() {
		taskId = SharedPreferencesUtil.getLong(this, WELCOME_IMG_ID);
		if (taskId != -1L) {
			showImgWelcome(taskId);
			return;
		}

		File file = new File(pathBig);
		if (!file.exists()) {
//			Toast.makeText(getApplicationContext(), "No file!", Toast.LENGTH_SHORT).show();
			return;
		}
		taskId = mDSKernel.sendFile(DSKernel.getDSDPackageName(), pathBig, new ISendCallback() {
			@Override
			public void onSendSuccess(long l) {
				showImgWelcome(taskId);
				SharedPreferencesUtil.put(getApplicationContext(), WELCOME_IMG_ID, taskId);
			}

			@Override
			public void onSendFail(int i, String s) {
			}

			@Override
			public void onSendProcess(long l, long l1) {
			}
		});
	}

	private void showImgWelcome(long taskId) {
		String json1 = UPacketFactory.createJson(DataModel.SHOW_IMG_WELCOME,"");
		mDSKernel.sendCMD(DSKernel.getDSDPackageName(),json1,taskId,null);
	}

	private void Show(){
		Toast.makeText(LoginActivity.this,"1-------",Toast.LENGTH_SHORT).show();
		final DSKernel mDSKernel = DSKernel.newInstance();
		mDSKernel.init(getApplicationContext(), new IConnectionCallback() {
			@Override
			public void onDisConnect() {

			}

			@Override
			public void onConnected(ConnState state) {

			}
		});
		mDSKernel.addReceiveCallback(new IReceiveCallback() {
			@Override
			public void onReceiveData(DSData data) {

			}

			@Override
			public void onReceiveFile(DSFile file) {

			}

			@Override
			public void onReceiveFiles(DSFiles files) {

			}

			@Override
			public void onReceiveCMD(DSData cmd) {

			}
		});
		JSONObject json = new JSONObject();
		try {
			json.put("interval",5000); //幻灯片的切换时间，用毫秒计算，如果不传默认是10000毫秒
		} catch (JSONException e) {
			e.printStackTrace();
		}
		List pathList = new ArrayList<>();
		pathList.add("/storage/emulated/0/sunmi1.png");
		pathList.add("/storage/emulated/0/sunmi2.png");
		pathList.add("/storage/emulated/0/sunmi3.png");
		pathList.add("/storage/emulated/0/sunmi4.png");
		mDSKernel.sendFiles(DSKernel.getDSDPackageName(), json.toString(),
				pathList, new ISendFilesCallback() {
					@Override
					public void onAllSendSuccess(long fileid) {
						show(fileid);
					}

					@Override
					public void onSendSuccess(String path, long taskId) {

					}

					@Override
					public void onSendFaile(int errorId, String errorInfo) {
						Toast.makeText(LoginActivity.this,"onSendFaile----"+errorInfo,Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onSendFileFaile(String path, int errorId, String errorInfo) {
						Toast.makeText(LoginActivity.this,"onSendFileFaile----"+errorInfo,Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onSendProcess(String path, long totle, long sended) {

					}
				});
	}

	private void show(long fileId) {
		Toast.makeText(LoginActivity.this,"成功-------",Toast.LENGTH_SHORT).show();
		String json = UPacketFactory.createJson(DataModel.IMAGES,"");
		mDSKernel.sendCMD(DSKernel.getDSDPackageName(),json,fileId,null);
	}

}
